package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxLcxx;
import cn.wizzer.app.bus.modules.models.YJbxxLzxx;
import cn.wizzer.app.bus.modules.services.YJbxxLcxxService;
import cn.wizzer.app.bus.modules.services.YJbxxLzxxService;
import cn.wizzer.app.bus.modules.services.YJbxxService;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 样品移交  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/ypxx/yj")
public class YyjController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLzxxService yjbxxlzxxservice;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private ShiroUtil shiroUtil;

    @At("/?")
    @Ok("beetl:/platform/bus/ypxx/yj/list.html")
    @RequiresPermissions(value = {"bus.ypxx.yj.list"},logical = Logical.OR)
    public void index(String lzzt ,HttpServletRequest req) {
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));
        req.setAttribute("lzztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lzzt")));
        req.setAttribute("lzzt", lzzt);
        req.setAttribute("userId", StringUtil.getPlatformUid());
        req.setAttribute("type", "two");
    }

    @At("/")
    @Ok("beetl:/platform/bus/ypxx/yj/list.html")
    @RequiresPermissions(value = {"bus.ypxx.yj.list1"},logical = Logical.OR)
    public void indexYj(HttpServletRequest req) {
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        req.setAttribute("lzztMap", JSONObject.fromObject(sysDictService.getCodeMap("lzzt")));
        req.setAttribute("lzztOptions", JSONArray.fromObject(sysDictService.dictCodeTree("lzzt")));
        req.setAttribute("lzzt", "0");
        req.setAttribute("userId", StringUtil.getPlatformUid());
        req.setAttribute("type", "one");
    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("lzzt") String lzzt,@Param("type") String type,@Param("thisLzzt") String thisLzzt, @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            //String sql ="SELECT (select status from y_jbxx_lzxx lzxx where lzxx.jbxxId = jbxx.id and lzxx.lzzt = jbxx.lzzt and lzxx.nextsprIds =jbxx.jsr) status,jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx,jbxx.jsr,jbxx.opBy" +
                    //" FROM y_jbxx jbxx where 1=1 and jbxx.lczt>0 and jbxx.delflag = 0 ";
            String sql ="select * from (select jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx, jbxx.jyfy,jbxx.jsr,jbxx.opBy,jbxx.opAt, " +
                    "lzxx.id as lzxxid, lzxx.lzAt,lzxx.number,lzxx.jhwcqx,lzxx.nextsprIds,lzxx.nextspr,lzxx.statusAt,lzxx.status" +
                    ",(select username from sys_user u where u.id = lzxx.opBy) as fqr " +
                    "from y_jbxx jbxx left join y_jbxx_lzxx lzxx  on lzxx.jbxxId = jbxx.id and lzxx.lzzt = jbxx.lzzt " +
                    "LEFT JOIN y_jbxx_lzxx lzxx2 ON lzxx2.jbxxId = jbxx.id AND lzxx2.lzzt = jbxx.lzzt and lzxx2.opAt>lzxx.opAt " +
                    "where 1=1 and lzxx2.opAt is null and jbxx.lczt>0 and jbxx.delflag = 0  ";

            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%')";
            }
            if (Strings.isNotBlank(lzzt)&&!lzzt.equals("")) {
                sql+= " and jbxx.lzzt = '"+lzzt+"' ";
            }
            if (Strings.isNotBlank(thisLzzt)&&!thisLzzt.equals("")) {
                if(type.equals("one")){//待移交 只能查询自己登记的 和自己接收的
                    sql+= " and jbxx.lzzt = "+thisLzzt+" ";
                }else{
                    sql+= " and jbxx.lzzt >= "+thisLzzt+" ";
                }
            }
            if(thisLzzt.equals("0")){//待移交 只能查询自己登记的 和自己接收的
                if(type.equals("one")){//待移交 只能查询自己登记的 和自己接收的
                    sql+= StringUtil.dataScopeFilter("jbxx");
                }else{
                    sql+= " and lzxx.nextsprIds = '"+StringUtil.getPlatformUid()+"'";
                }
            }else if(thisLzzt.equals("1")){//已移交，待退样,被移交人只能查看移交给自己的，退样给原人员
                sql+= " and jbxx.jsr = '"+StringUtil.getPlatformUid()+"' ";
            }else if(thisLzzt.equals("2")){//已退样，带归还 只能查询自己登记的 和自己退样的
                sql+= StringUtil.dataScopeFilter("jbxx");
            }else if(thisLzzt.equals("3")){//已归还 //只能查询自己的
                sql+= StringUtil.dataScopeFilter("jbxx");
            }

            sql+= " ) as a ";
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc ";
                } else {
                    sql+= " order by jbxx."+pageOrderName+" desc ";
                }
            }else{
                sql+= " order by opAt desc ";
            }
            //yjbxxService.listPageMap()Page(pageNumber,pageSize, Sqls.create(sql));
            return Result.success().addData(yjbxxService.listPageMap(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/toDetail/?")
    @Ok("json")
    @RequiresAuthentication
    public Object toDetail(String id) {
        YJbxx obj = yjbxxService.fetch(id);
        obj.setYjsj(DateUtil.getDateTime());
        obj.setYjr(shiroUtil.getPrincipalProperty("id").toString());//
        Map map = new HashMap();
        map.put("obj",JSONObject.fromObject(obj));

        List<NutMap> treeList = new ArrayList<>();
        //map.put("yjrname",shiroUtil.getPrincipalProperty("username").toString());
        List<Sys_user> list = sysUserService.listEntity(Sqls.create("select * from sys_user where id !='"+StringUtil.getPlatformUid()+"'"));
        for (Sys_user sysUser : list) {
            NutMap map1 = NutMap.NEW().addv("value", sysUser.getId()).addv("label", sysUser.getUsername());
            treeList.add(map1);
        }
        map.put("userOptions",JSONArray.fromObject(treeList));
        try {
            return Result.success().addData(map);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "移交样品", msg = "样品:${args[0].ypbh}")
    public Object yjDo(@Param("..") YJbxx obj,@Param("..") YJbxxLzxx lzxxObj) {
        try {
            //obj.setOpBy(StringUtil.getPlatformUid());
            //obj.setOpAt(Times.getTS());
            lzxxObj.setStatus("0");
            lzxxObj.setNumber(obj.getYjsl());
            lzxxObj.setLzAt(obj.getYjsj());
            if(obj.getLzzt().equals("4")||obj.getLzzt().equals("3")){//归还和自行处置不需要确认，没有人确认
                lzxxObj.setStatus("1");
            }
            if(obj.getLzzt().equals("2")){//退样的接收人是登记人
                lzxxObj.setNextsprIds(obj.getOpBy());
                Sys_user user = sysUserService.fetch(obj.getOpBy());
                lzxxObj.setNextspr(user.getUsername());
                lzxxObj.setNumber(obj.getTysl());
            }
            if(!StringUtils.isEmpty(lzxxObj.getNextsprIds())){
                obj.setJsr(lzxxObj.getNextsprIds());
            }
            lzxxObj.setYpbh(obj.getYpbh());
            lzxxObj.setLzzt(obj.getLzzt());
            /*lzxxObj.setNextspr(obj.getJsr());
            lzxxObj.setNextsprIds(obj.getJsr());*/
            lzxxObj.setJbxxId(obj.getId());
            lzxxObj.setOpBy(StringUtil.getPlatformUid());
            lzxxObj.setOpAt(Times.getTS());
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxService.updateIgnoreNull(obj);
                    yjbxxlzxxservice.insert(lzxxObj);
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    @SLog(tag = "接收样品", msg = "样品:${args[0].ypbh}")
    public Object jsDo(@Param("..") YJbxx obj,@Param("..") YJbxxLzxx lzxxObj,@Param("lzxxid") String lzxxid,@Param("fqr") String fqr) {
        try {
            if(lzxxObj.getStatus().equals("1")){
                YJbxxLzxx lzxx = yjbxxlzxxservice.fetch(lzxxid);
                lzxx.setStatus(lzxxObj.getStatus());
                lzxx.setStatusAt(lzxxObj.getStatusAt());
                yjbxxlzxxservice.update(lzxx);
            }else if(lzxxObj.getStatus().equals("-1")){
                YJbxx jbxx = yjbxxService.fetch(obj.getId());
                lzxxObj.setStatus("-1");
                lzxxObj.setYpbh(jbxx.getYpbh());
                lzxxObj.setJbxxId(jbxx.getId());
                //lzxxObj.setLzzt(jbxx.getLzzt()-1);//退回状态-1
                lzxxObj.setLzAt(DateUtil.getDateTime());
                lzxxObj.setJhwcqx("");
                lzxxObj.setNextsprIds(lzxxObj.getOpBy());//退回接收人是发起人
                lzxxObj.setNextspr(fqr);
                lzxxObj.setOpBy(StringUtil.getPlatformUid());
                lzxxObj.setOpAt(Times.getTS());

                jbxx.setJsr(lzxxObj.getOpBy());//退回接收人是发起人
                //jbxx.setLzzt(jbxx.getLzzt()-1);
                Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                    public void run() {
                        yjbxxService.updateIgnoreNull(jbxx);
                        yjbxxlzxxservice.insert(lzxxObj);
                    }
                });
            }

            return Result.success("操作成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }
}
